package com.obst.tracenote;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.androidquery.AQuery;
import com.androidquery.auth.FacebookHandle;
import com.androidquery.callback.AjaxStatus;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ImageButton;
import android.widget.Toast;

public class LoginActivity extends Activity {
	private String mFacebookAccessToken;
	private FacebookHandle handle;
	private final int ACTIVITY_SSO = 1000;
	private AQuery aq = new AQuery(LoginActivity.this);
	private static String FB_PERMISSIONS = "read_stream,read_friendlists,manage_friendlists,manage_notifications,publish_stream,publish_checkins,offline_access,user_photos,user_likes,user_groups,friends_photos";
	private ImageButton btnLogin;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.loginactivity);
		btnLogin = (ImageButton) findViewById(R.id.login_btn);

		btnLogin.setOnClickListener(new ImageButton.OnClickListener() {
			public void onClick(View v) {
				auth_facebook_sso();
			}
		});
	}

	public void auth_facebook_sso() {

		handle = new FacebookHandle(this, C.FACEBOOK_APP_ID, FB_PERMISSIONS);
		handle.sso(ACTIVITY_SSO);

		String url = "https://graph.facebook.com/me/feed";
		aq.auth(handle).ajax(url, JSONObject.class, this, "facebookCb");

	}

	public void facebookCb(String url, JSONObject jo, AjaxStatus status) {

		String[] SOURCE = { "", "NETWORK", "DATASTORE", "FILE", "MEMORY" };
		String meta = "fail";
		String str = "fail";
		if (status != null) {
			meta = "Source:" + SOURCE[status.getSource()]
					+ "\nResponse Code:" + status.getCode() + "\nDuration:"
					+ status.getDuration() + "ms";
			if (status.getCode() != 200) {
				meta = meta + "\nMessage:" + status.getMessage();
			}
		}
		if(jo != null){
			try {
				str = jo.toString(2);
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}		
		Log.v(C.LOG_TAG, "fb status : " + meta);
		Log.v(C.LOG_TAG, "fb return : " + str);
		Log.v(C.LOG_TAG, "fb url : " + url);
		Toast.makeText(LoginActivity.this, "success", Toast.LENGTH_LONG).show();
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {

		switch (requestCode) {

		case ACTIVITY_SSO: {
			if (handle != null) {
				handle.onActivityResult(requestCode, resultCode, data);
			}
			break;
		}

		}
	}
}
